<template>
  <div class="my-upload-file">
    <file-move v-model="fileList">
      <el-upload
        class="upload-demo"
        :action="mainAction"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="successHandle"
        :headers="headers"
        v-bind="$attrs" v-on="$listeners"
        :file-list="fileList">
        <el-button size="small" type="primary" icon="el-icon-upload">
          <slot>点击上传</slot>
        </el-button>
        <div slot="tip" class="el-upload__tip" v-if="desc">{{desc}}</div>
      </el-upload>
      <preview-file :files="previewUrl" v-if="previewUrl&&visible" :visible.sync="visible"></preview-file>
    </file-move>
  </div>
</template>
<script>
  import PreviewFile from "./PreviewFile";
  import FileMove from "./FileMove";
  import {getToken} from "@/utils/auth"; // 获取登录用户信息
  export default {
    model: {
      prop: "value",
      event: "input"
    },
    name: "MyUploadFile",
    components: {FileMove, PreviewFile},
    props: {
      value: {
        type: String,
        default: undefined
      },
      desc: {
        type: String,
        default: undefined
      },
      previewOrDownload: {
        type: String,
        default: 'preview'
      },
      uploadUrl: {
        type: String,
        default: '/api/upload_file/'
      }
    },
    data() {
      return {
        previewUrl: "",
        visible: false,
        fileList: []
      }
    },
    created() {

    },
    mounted() {
      this.fileList = this.initFilesList()
    },
    watch: {//此处只能用watch，如果用computed的话会导致整个列表重新渲染，体验不好
      value(newVal, oldVal) {
        if (newVal != this.getFileList(this.fileList)) {
          this.fileList = this.initFilesList()
        }
      },
      fileList: {
        handler(newValue, oldValue) {
          let files = this.getFileList(newValue)
          if (this.value != files) {
            this.$emit("input", files)
          }
        },
        deep: true,
      }
    },
    computed: {
      headers() {
        return {
          Authorization: "JWT " + getToken()
        };
      },
      mainAction() {
        return process.env.VUE_APP_BASE_API + this.uploadUrl;
      },
    },
    methods: {
      initFilesList() {
        if (this.value) {
          let fileList = []
          let _list = this.value.split(",")
          for (let i = 0; i < _list.length; i++) {
            let _ary = _list[i].split("|")
            let _name = _ary[0]
            fileList.push({name: _name, url: process.env.VUE_APP_BASE_API + _ary[1] + "?title=" + _name, id: i, realUrl: _ary[1]})
          }
          return fileList
        } else {
          return []
        }
      },
      getFileList(list) {
        let _files = list.map(item => {
          return item.name + "|" + item.realUrl
        }).join(",")
        return _files
      },
      handlePreview(file) {
        if (this.previewOrDownload == "download") {
          window.open(file.url)
        } else {
          this.visible = true
          this.previewUrl = file.realUrl
        }
      },
      handleRemove(file, fileList) {
        // this.fileList = fileList.filter(item => {
        //     return item.uid != file.uid
        // })
        this.fileList = fileList
        this.$emit("input", this.getFileList(fileList))
      },
      successHandle(res, file, fileList) {
        if (res.code == 0) {
          this.$set(this.fileList, this.fileList.length, {
            name: file.name,
            url: process.env.VUE_APP_BASE_API + res.data.file_path,
            realUrl: res.data.file_path,
            uid: file.uid
          })
          this.$emit("input", this.getFileList(this.fileList))
        }
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isLt2M) {
          this.$message.error('文件不能超过 20MB!');
        }
        return isLt2M;
      }
    }
  }
</script>
<style lang="scss" scoped>
  .el-upload__tip {
    margin-right: 10px;
    line-height: 20px;
  }
</style>
